//
//  UUPermissionManager.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 08/03/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUPermissionManager.h"
#import "UUUserManager.h"

@interface UUPermissionManager ()

@property (nonatomic, copy) NSDictionary<NSString *, NSSet *> *permissions;

@end

@implementation UUPermissionManager

- (instancetype)init {
    self = [super init];
    if (self) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Permission" ofType:@"plist"];
        NSDictionary *rawPermissions = [NSDictionary dictionaryWithContentsOfFile:path];
        
        NSMutableDictionary<NSString *, NSSet *> *permissions = [NSMutableDictionary dictionaryWithCapacity:rawPermissions.count];
        [rawPermissions enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray<NSNumber *> *obj, BOOL * _Nonnull stop) {
            [permissions setObject:[NSSet setWithArray:obj] forKey:key];
        }];
        self.permissions = permissions;
    }
    return self;
}

- (BOOL)checkPermission:(UUPermissionFlag)flag {
    UUPermissionRoleType roleId = [GetUserManager() fetchUserInfo].roleId;
    if (roleId == UUPermissionRoleTypeOwner || roleId == UUPermissionRoleTypeSuperAdmin) {
        return YES;
    } else {
        NSString *roleKey = INT_TO_STRING(roleId);
        NSSet *flags = self.permissions[roleKey];
        return [flags containsObject:@(flag)];
    }
}

@end
